package main

import (
	"log"
	"strings"

	"github.com/panjf2000/gnet"
)

type udpEchoServer struct {
	*gnet.EventServer
}

func (es *udpEchoServer) OnInitComplete(srv gnet.Server) (action gnet.Action) {
	log.Printf("UDP Echo server is listening on %s (multi-cores: %t, loops: %d)\n",
		srv.Addr.String(), srv.Multicore, srv.NumEventLoop)
	return
}

func (es *udpEchoServer) React(frame []byte, c gnet.Conn) (out []byte, action gnet.Action) {
	// Echo synchronously.
	//out = frame
	//log.Printf("udp server recv from %s to %s,data is %s", c.RemoteAddr().String(), c.LocalAddr().String(), string(out))
	//return

	/*
		// Echo asynchronously.
		data := append([]byte{}, frame...)
		go func() {
			time.Sleep(time.Second)
			c.SendTo(data)
		}()
		return
	*/

	var cmd = string(frame[1:])
	if strings.Contains(cmd, "DEVKEY") {
		var key = strings.Split(cmd, ":")[1]
		key = strings.Split(key, "\r\n")[0]
		var strArr = strings.Split(c.RemoteAddr().String(), ":")
		var ci ConnInfo
		ci.conn = c
		ci.connKey = key
		ci.connIp = strArr[0]
		ci.connPort = strArr[1]
		connMap.Set(key, ci)
	}

	return
}

func udp_echo() {
	/*var udpPort int
	var multicore, reuseport bool

	// Example command: go run echo.go --port 9000 --multicore=true --reuseport=true
	flag.IntVar(&udpPort, "port", 9002, "--port 9002")
	flag.BoolVar(&multicore, "multicore", false, "--multicore true")
	flag.BoolVar(&reuseport, "reuseport", false, "--reuseport true")
	flag.Parse()*/
	udpEcho := new(udpEchoServer)
	//log.Fatal(gnet.Serve(udpEcho, fmt.Sprintf("udp://:%9002", udpPort), gnet.WithMulticore(false), gnet.WithReusePort(false)))
	log.Fatal(gnet.Serve(udpEcho, "udp://:9002", gnet.WithMulticore(true), gnet.WithReusePort(false)))
}
